
/*
 * for 64-bit mode ??
*/

#include "hw2_common.h"

void process_file(char *file);


int main ( int argc, char **argv)
{
    char *file; // = (char*)malloc(256*sizeof(char));

    if (argc != 2)
        exit(1);
    else
        file = argv[1];
    
    process_file(file);

    // free(file);      // seg fault here

    return 0;
}


void process_file(char *file) {

    int fd;

    // create a file descriptor
    fd = my_open( file, O_RDONLY);

    //printf("file descriptor: %d \n", fd);

    // store 1-byte from file in here
    char *buff = (char*) malloc(sizeof(char));          
    
    printf("\n");

    while (1) 
    {
        pid_t procid = my_fork();

        if (procid != 0) {      // parent process
            
            //printf("in parent \n");
            //int pid = getpid();

            //printf("Current process's id: %d \n", pid);

            int p_status;

            // block until child process terminates
            my_waitpid(procid, &p_status, 0);

            // non-zero if child terminated normally
            if ( WIFEXITED(p_status) != 0 )
            {
                //printf("status of child = %d \n", WEXITSTATUS(p_status));
                
                if ( WEXITSTATUS(p_status) == 2 )
                    break;
            }
        }
        else {     // in child process             
            //printf("in child \n");

            // read 1 byte from file
            // 0 byte read means end-of-file
            int bytes_read = my_read(fd, buff, 1);

            // write to standard output, i.e. console
            my_write(1, buff, 1);

            // return exit code of 2 if end-of-file
            if (bytes_read == 0)                
                _exit(2);        
            else
                _exit(0);
        }
    }

    printf("\n");

    my_close(fd);

    free(buff);    
}
